<?php 

//define('COOKIELOCAL', str_replace('\\', '/', realpath('../')) . '/' . 'cookies_cnpjs/');
define('COOKIELOCAL', str_replace('\\', '/', realpath('../')) . '/' . 'cookies_prefeitura_anapolis/');
@session_start();

$cookieFile = COOKIELOCAL . session_id();

// cria arquivo onde será salva a sessão com a receita
if (!file_exists($cookieFile)) {
    $file = fopen($cookieFile, 'w');    
    fclose($file);
}

$url = 'http://www.anapolis.go.gov.br/certidao/captcha.php?rnd=0.6778794799465686';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

$imgsource = curl_exec($ch);
curl_close($ch);

$saveto = '../images/image.png';

if (file_exists($saveto)) {
    unlink($saveto);
}

$fp = fopen($saveto, 'x');
fwrite($fp, $imgsource);
fclose($fp);

?>
<html>
    <head>
        <title>CNPJ e Captcha</title>
    </head>
    <body> 
        <?php include_once 'carregando.php' ; ?>
        <form name="emitirCND" id="emitirCND" method="post" action="<?php echo base_url('index.php/certidoes/processa_prefeitura_anapolis') ?>">
            <p>
                <input type="hidden" name="tipoDocumento" value="CNPJ"  /> 
                <input type="hidden" name="numeroDocumento" value="<?php echo $pessoa->pessoas_cnpj?>"  /> 
                <input type="hidden" name="finalidade" value="Outras" required /> 
                <input type="hidden" name="interesse" value="Outros" />                
                <?php
                        $objCaptcha = new Captcha_Model();
                        $objCaptcha->setFileName($saveto);
                ?>
                <input type="hidden" name="captcha" maxlength="4" value="<?php $objCaptcha->submeterCaptcha(); ?>" required  />
            </p>
            <p>
            </p>
        </form>
</html>

<script>
    document.getElementById("emitirCND").submit();
</script>